<?php

namespace App\Recharge\Traits;

use App\Models\Admin\Supplier;
use App\Recharge\Logic\ConfigLogic;
use App\Models\Admin\InterfaceConfiguration;
use App\Recharge\Interfaces\ApiInterface;
use App\Recharge\Exceptions\SuspensionOfEnforcement;

trait RechargeTraits
{
    /**
     * @var string
     */
    protected string $apiInterfacePrefix = "App\Recharge\Api";

    /**
     * 获取api
     *
     * @param array $child
     * @param Supplier $supplier
     * @return InterfaceConfiguration
     * @throws SuspensionOfEnforcement
     */
    final protected function api(array $child, Supplier $supplier): InterfaceConfiguration
    {
        // 获取api
        $api = ConfigLogic::new($supplier)->getApiConfig($child['goods_belong']);
        if (in_array($api->id, [1,2,8])) {
            throw new SuspensionOfEnforcement(sprintf("%s不继续往下走", $api->title));
        }
        return $api;
    }

    /**
     * @param string $method
     * @return string
     */
    final public function makeApiClassName(string $method): string
    {
        return sprintf("%s\%s", $this->apiInterfacePrefix, ucfirst($method));
    }

    /**
     * @param InterfaceConfiguration $config
     * @return ApiInterface
     * @throws SuspensionOfEnforcement
     */
    final public function obtainApiInterface(InterfaceConfiguration $config): ApiInterface
    {
        $classes = [$this->makeApiClassName($config->en)];
        // 判断是否有相似的
        if ($config->same_api_en != "" && $config->same_api_en != $config->en) {
            array_unshift($classes, $this->makeApiClassName($config->same_api_en));
        }
        foreach ($classes as $classname) {
            $class = instantiationClass($classname, ApiInterface::class);
            if ($class) {
                return $class;
            }
        }
        throw new SuspensionOfEnforcement("未定义接口数据方法[".$config->title."]");
    }

}
